//赠品活动列表表格
var $customerProductGiftActivityTable = $('#customerProductGiftActivityTableList');
//防止表头与表格不对齐
$(window).resize(function () {
    $customerProductGiftActivityTable.bootstrapTable('resetView');
});
//初始化赠品活动列表页
$(function () {
    customerProductGiftActivityTableListInit();

    // 重置表单
    $('#btn-reset').on('click', function () {
        $('#btn-search-simple').prev('input').val('');
        resetSearch.call(this, customerProductGiftActivityTableListInit);
    });
    // 高级搜索
    $('#btn-search').on('click', function () {
        search($customerProductGiftActivityTable, advancedQueryParams);
    });
    // 简单搜索
    $('#btn-search-simple').on('click', function () {
        search.call(this, $customerProductGiftActivityTable, queryParams);
    });

    // 活动起止时间
    $('#giftActivityPeriodValidity').daterangepicker({
        timePicker: true,
        startDate: moment().startOf('hour'),
        endDate: moment().startOf('hour').add(24, 'hour'),
        locale: {
            format: 'YYYY-MM-DD HH:mm',
            cancelLabel: '清空',
        },
        timePicker24Hour : true,
        autoUpdateInput: false,
    });
    $('#giftActivityPeriodValidity').on('apply.daterangepicker', function(ev, picker) {
        $(this).val(picker.startDate.format('YYYY-MM-DD HH:mm') + ' 至 ' + picker.endDate.format('YYYY-MM-DD HH:mm'));
    });
    $('#giftActivityPeriodValidity').on('cancel.daterangepicker', function(ev, picker) {
        $(this).val('');
    });
});

/**
 * 初始化赠品活动列表
 * @Atuhor yincuimei
 */
function customerProductGiftActivityTableListInit(){
    //先销毁表格
    $customerProductGiftActivityTable.bootstrapTable('destroy');
    $customerProductGiftActivityTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/customerProductGiftActivity/selectCustomerProductGiftActivityList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'productGiftActivityId',
        idField: 'productGiftActivityId',
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数

        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber: 2,    // 右侧固定列

        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'productGiftActivityId', visible: false},
            {title: '产品分类', field: 'productCategories', visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '52', formatter: indexFormat},
            {title: '赠品活动名称',field: 'giftActivityName',align: 'left', valign: 'middle', width: '120', class: 'ellipsis'},
            {title: '产品名称', field: 'productName',align: 'left', valign: 'middle', width: '120', class: 'ellipsis'},
            {title: '赠品类别', field: 'giftCategory',align: 'left', valign: 'middle'},
            {title: '价格区间', field: 'giftActivityPriceSection',align: 'left', valign: 'middle'},
            {title: '起止时间', field: 'giftActivityPeriodValidity', align: 'left',valign: 'middle',formatter: timeInterval},
            {title: '兑换方式', field: 'exchangeMethod',align: 'left',valign: 'middle'},
            {title: '创建人', field: 'createPeopleName',align: 'left',valign: 'middle'},
            {title: '创建时间', field: 'createTm',align: 'left',valign: 'middle',sortable: true},
            {title: '操作',field:'operate', align:'right',width:'112',events:operateEvents,formatter: genderOpt},
            {title: '是否上架',field:'giftShelfStatus',align:'right',width:'80',formatter: operateGiftShelfStatusFormat}
        ],
        responseHandler: function (result) {
            if(result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function (data) {
            // table操作列下拉菜单效果
            tableNav();

            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#customerProductGiftActivityTableList').css({
                minWidth: $('#customerProductGiftActivityTableList').width()
            }).colResizable({
                resizeMode: 'overflow',
                liveDrag: true,
                gripInnerHtml: "<div class='grip'></div>",
                draggingClass: "dragging",
                disabledColumns: [0, 3, 4, 5, 6, 7, 8, 9, 10, 11],          // 禁止拖动的列
                postbackSafe: true,                                         // 刷新后保持拖动的宽度
                partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
                flush: true,
                minWidth: 80
            });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

/**
 * 拼接赠品活动列表查询条件参数
 * @Author yincuimei
 */
function queryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    //普通搜索条件
    params.giftActivityName = $.trim($('#giftActivityNameMin').val());//赠品活动名称
    return params;
}

/**
 * 拼接赠品活动列表高级查询条件参数
 * @Author yincuimei
 */
function advancedQueryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.defaultMark = $('#defaultMark').val();//是否是默认池

    //清空普通搜索条件
    $('#giftActivityNameMin').val('');//赠品活动名称

    params.productName = $.trim($('#productName').val());//产品名称
    params.giftCategory = $('#giftCategorySelect option:selected').val();//赠送类别
    params.giftActivityPriceStart = $('#giftActivityPriceStart').val();//赠品活动价格起始价
    params.giftActivityPriceEnd = $('#giftActivityPriceEnd').val();//赠品活动价格截止价

    if($('#giftActivityPeriodValidity').val()){
        var giftActivityPeriodValidity = $('#giftActivityPeriodValidity').val().split(" 至 ");//赠品活动时间(区间)
        if(giftActivityPeriodValidity.length > 0){
            params.giftPeriodValidityStart = giftActivityPeriodValidity[0];  //赠品活动开始时间
            params.giftPeriodValidityEnd = giftActivityPeriodValidity[1];    //赠品活动结束时间
        }
    }
    return params;
}

/**
 * 赠品活动列表--列表序列号
 * @Author yincuimei
 */
function indexFormat(value, row, index) {
    return index + 1;
}

/**
 *赠品活动列表--自定义操作列内容
 * @Author yincuimei
 */
function genderOpt(value, row, index) {
    let html = '';
    html += '<button type="button" class="btn btn-default" id="detail"><i class="mdi mdi-eye"></i>查看</button>';
    html += '<div class="dropdown"><button class="btn btn-link" data-index="' + index + '"><i class="mdi mdi-dots-vertical"></i></button><ul class="dropdown-menu">';
    html += '<li><a class="js-create-tab" data-title="编辑赠品活动" data-url="/front/activityManager/editProductGift?giftId=' + row.productGiftActivityId+'">编辑</a></li>';
    html += '<li><a href="#!" id="delete">删除</a></li>';
    html += '</ul></div>';
    return html;
}
/**
 * 赠品活动列表--时间区间
 * @Author yincuimei
 */
function timeInterval(value, row, index) {
    // console.log(value, row, index)
    let html = row.giftPeriodValidityStart + ' 至 ' + row.giftPeriodValidityEnd;
    return html;
}

/**
 *赠品活动列表--自定义操作列事件
 * @Author yincuimei
 */
window.operateEvents = {
    //查看赠品活动
    'click #detail': function(e, value, row, index) {

        showProductGiftActivityInfo(row);   // 展示赠品活动--赠品列表信息

        var giftShelfStatus = Number(row.giftShelfStatus);      // 上下架状态
        var giftCategory = row.giftCategory;                    // 赠品类别(价格类/产品类)

        // 上下架状态处理
        if (giftShelfStatus) {
            // 1-下架
            $('.activity-status .icon').html('<i class="mdi mdi-do-not-disturb"></i>');
            $('.activity-status .status-text').html('下架');
        } else {
            // 0-上架
            $('.activity-status .icon').html('<i class="mdi mdi-check-circle"></i>');
            $('.activity-status .status-text').html('上架');
        }
        // 赠品类型区分
        var infoHtml = '';
        if (giftCategory == '产品类') {
            // 产品类
            infoHtml += '<h5>' + row.giftActivityName + '<span>产品类</span></h5>';
            infoHtml += '<span>活动起止日期</span><p>' + row.giftPeriodValidityStart + '<span>至</span>' + row.giftPeriodValidityEnd + '</p>';
            infoHtml += '<span>产品名称</span><p>' + row.productName + '</p>';
        } else {
            // 价格类
            infoHtml += '<h5>' + row.giftActivityName + '<span class="type_price">价格类</span></h5>';
            infoHtml += '<span>活动起止日期</span><p>' + row.giftPeriodValidityStart + '<span>至</span>' + row.giftPeriodValidityEnd + '</p>';
            infoHtml += '<span>价格区间</span><p>' + row.giftActivityPriceSection + '</p>';
        }
        $('#detailProductGiftActivityContent .activity-info').html(infoHtml);
        
        $('#detailProductGiftActivityContent').modal('show');    // 查看赠品活动
    },

    //删除赠品活动
    'click #delete': function(e, value, row, index) {
        $.alert({
            title: '提示',
            content: "确定要删除吗？",
            buttons: {
                confirm: {
                    text: '确认',
                    btnClass: 'btn-primary',
                    action: function () {
                        $.ajax({
                            type: "post",
                            url: "/customerProductGiftActivity/deleteCustomerProductGiftActivity",
                            data: {
                                productGiftActivityId: row.productGiftActivityId
                            },
                            dataType: 'json',
                            success: function (data, status) {
                                if (data.code == '000000') {
                                    $.alert('操作成功!');
                                    $customerProductGiftActivityTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                                } else {
                                    $.alert(data.message);
                                }
                            },
                            error: function () {
                                $.alert('修改失败，请稍后再试!');
                            }
                        });
                    }
                },
                cancel: {
                    text: '取消',
                    action: function () {
                    }
                }
            }
        })
    }
};

/**
 * 赠品活动上/下架列显示
 * @Author yincuimei
 */
function operateGiftShelfStatusFormat(value, row, index){
    var is_checked = '';
    let shelfStatus = '';
    var newShelfStatus;
    if(value == null || value == undefined) {
        return '';
    }else if(value == 0) {
        is_checked = 'checked="checked"';
        newShelfStatus = 1;
    } else if (value == 1) {
        is_checked = '';
        newShelfStatus = 0;
    }
    var shelfStatusHtml = '<label class="lyear-switch switch-solid switch-success">' +
        '<input type="checkbox" id="shelfStatus' + row.productGiftActivityId  + '" ' + is_checked + '>' +
        '<span onClick="updateActivityShelfStatus(\'' + row.productGiftActivityId + '\', \'' + newShelfStatus + '\')"></span>' +
        '</label>';
    return shelfStatusHtml;
}

/**
 * 赠品活动上/下架操作
 * @param productGiftActivityId  ---赠品活动主键
 * @param shelfStatus            ---上/下架状态
 * @Author yincuimei
 */
function updateActivityShelfStatus(productGiftActivityId,shelfStatus){
    var confirmMessage = '';
    if (shelfStatus == 0) {
        //判断是否在活动有效期内
        $.ajax({
            type: "post",
            url: "/customerProductGiftActivity/selectGiftActivityIsInValidityPeriod",
            data: {
                productGiftActivityId: productGiftActivityId
            },
            dataType: 'json',
            async: false,
            success: function (data, status) {
                if(data.code == '000000') {
                    confirmMessage = "确定上架吗？";
                    sendUpdateGiftActivityShelfStatus(productGiftActivityId,shelfStatus,confirmMessage);
                }else{
                    $.alert("活动已结束不能上架");
                    $("#shelfStatus" + productGiftActivityId).prop('checked',true);
                }
            },
            error:function(){
                $.alert("操作失败,请稍后再试!");
            }
        });
    } else {
        confirmMessage = "确定下架吗？";
        sendUpdateGiftActivityShelfStatus(productGiftActivityId,shelfStatus,confirmMessage);
    }
}

/**
 * 赠品活动上/下架调用后端接口
 * @param productGiftActivityId  ---赠品活动主键
 * @param shelfStatus            ---上/下架状态
 * @param confirmMessage         ---提示信息
 * @Author yincuimei
 */
function sendUpdateGiftActivityShelfStatus(productGiftActivityId,shelfStatus,confirmMessage){
    $.alert({
        title: '提示',
        content: confirmMessage,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/customerProductGiftActivity/updateGiftActivityShelfStatus",
                        data: {
                            productGiftActivityId: productGiftActivityId,//活动ID
                            giftShelfStatus: shelfStatus  //上/下架状态
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.code == '000000') {
                                $customerProductGiftActivityTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                            } else {
                                $.alert(data.message);
                                $customerProductGiftActivityTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                            }
                        },
                        error: function () {
                            $.alert('修改失败，请稍后再试!');
                            $customerProductGiftActivityTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                    if(shelfStatus == 1){//原先是上架状态
                        $("#shelfStatus" + productGiftActivityId).prop('checked',true);
                    }else {//原先是下架状态
                        $("#shelfStatus" + productGiftActivityId).prop('checked',false);
                    }
                }
            }
        }
    });
}

/**
 * 赠品活动查看信息展示
 * @Author yincuimei
 * @param row
 */
function showProductGiftActivityInfo(row){
    $.ajax({
        type: "post",
        url: "/customerProductGiftActivity/detailCustomerProductGiftActivity",
        data: {
            productGiftActivityId:  row.productGiftActivityId,//赠品活动ID
            productCategories:  row.productCategories,//产品分类
            giftCategory:  row.giftCategory //赠品类别:价格类/产品类
        },
        dataType: 'json',
        async: false,
        success: function (data, status) {
            if(data.code == '000000') {
                if(data.code == '000000') {
                    console.log(data);
                    var data = data.data;
                    //赠品活动名称--data.giftActivityName;产品名称--data.productName;价格区间--data.giftActivityPriceStart,data.giftActivityPriceEnd
                    //活动起止时间--data.giftPeriodValidityStart,data.giftPeriodValidityEnd
                    //上/下架状态giftActivityShelfStatusFormat(data.giftShelfStatus)
                    //相关赠品--data.customerProductGiftList(数组集合)[{"productId":'',"productName":''}]

                    // 获取赠品列表
                    var giftListHtml = '';
                    for (var i = 0; i < data.customerProductGiftList.length; i++) {
                        giftListHtml += '<span>' + data.customerProductGiftList[i].productName + '</span>'
                    }
                    $('#detailProductGiftActivityContent .activity-gift p').html(giftListHtml);
                }
            }
        },
        error:function(){
            $.alert("操作失败,请稍后再试!");
        }
    });
}

/**
 * 赠品活动查看--赠品活动上下架显示格式化
 * @param giftShelfStatus ---上/下架状态
 * @Author yincuimei
 * @returns {string}
 */
function giftActivityShelfStatusFormat(giftShelfStatus){
    if (giftShelfStatus == null || giftShelfStatus == undefined) {
        return "";
    }else if(giftShelfStatus == 0){
        return "上架";
    }else if(giftShelfStatus == 1){
        return "下架";
    }else{
        return "";
    }
}

/**
 * 新增赠品活动
 * @Author yincuimei
 */
function addProductGiftActivity(){
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '新增赠品活动',
        url : "/front/activityManager/addProductGift"
    }, true)
}